package com.seata.logic.visualize.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seata.logic.visualize.dao.TblUserMoneyMapper;
import com.seata.logic.visualize.entity.TblUserMoney;
import com.seata.logic.visualize.service.TblUserMoneyService;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * @author 蚂蚁会花呗
 * @date 2021/9/9 11:48
 */
@Service
public class TblUserMoneyServiceImpl extends ServiceImpl<TblUserMoneyMapper, TblUserMoney> implements TblUserMoneyService {

    static Log log = LogFactory.getLog(TblUserMoneyServiceImpl.class);



    @Override
    public void decreaseMoney(Long userId, BigDecimal money) {
        log.info("开始扣减钱数！");
        //模拟扣减账户失败，全部回滚
        int a = 11/0;
        System.out.println(a);
        TblUserMoney tblUserMoney = getUserMoney(userId);
        setMoney(tblUserMoney,money);
        this.saveOrUpdate(tblUserMoney);
        log.info("扣减账户结束！");
    }

    /**
     * 获取用户的钱数
     * @param userId
     * @return
     */
    public TblUserMoney getUserMoney(Long userId){
        QueryWrapper<TblUserMoney> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(TblUserMoney::getUserId,userId);
        return this.getOne(queryWrapper);
    }

    /**
     * 计算钱数
     */
    public void setMoney(TblUserMoney tblUserMoney,BigDecimal money){
        //已用钱数
        BigDecimal used = tblUserMoney.getUsed().add(money);

        //剩余钱数
        BigDecimal residue = tblUserMoney.getTotalMoney().subtract(used);

        tblUserMoney.setUsed(used);
        tblUserMoney.setResidue(residue);
    }

}
